#!/usr/bin/env python3
# This file a part of SHM. Copyright (C) Tom Li 2013.
# License: LGPL version 3 or later.

from sh import useradd, groupadd, ln, chown, rm, setquota, chmod, touch, rc_update, usermod
import os
from getpass import getpass
import argparse
import mysql.connector as db
from config import Config
CONFIG = "/var/shm/config"


def create_user(username, password):
    groupadd(username)
    useradd("-g", username,
            "-G", "wheel",
            "-s", "/bin/bash",
            "-m",
            username)
    usermod("-G", username,
            "-a", "nginx")
    os.system("echo \"%s:%s\" | chpasswd" % (username, password))


def create_database(username, password):
    while 1:
        root_password = getpass("Enter root password of MySQL: ")
        try:
            conn = db.connect(host='localhost', user='root', password=root_password)
            break
        except mysql.connector.errors.ProgrammingError:
            continue
    cursor = conn.cursor()
    cursor.execute(r"CREATE DATABASE %s;" % (username))
    cursor.execute(r"CREATE USER '%s'@'localhost' IDENTIFIED BY '%s';"
                   % (username, password))
    cursor.execute(r"GRANT ALL PRIVILEGES ON %s.* to %s@localhost;"
                   % (username, username))
    conn.close()


def create_quota(username, hard):
    soft = int(hard * 0.85)
    setquota("-u", username, soft, hard, "0", "0", "/home")


def create_domain(username, domain):
    config_name = "/etc/nginx/sites-available/%s.conf" % domain
    access_log_name = "/var/log/virtualhost/%s_access_log" % domain
    error_log_name = "/var/log/virtualhost/%s_error_log" % domain
    home_access_log = "/home/%s/logs/%s_access_log" % (username, domain)
    home_error_log = "/home/%s/logs/%s_error_log" % (username, domain)
    user_group = "%s:%s" % (username, username)

    os.system("./nginx_conf %s %s > %s" % (username, domain, config_name))

    chown("%s:%s" % (username, username), config_name)

    touch(access_log_name)
    touch(error_log_name)
    ln("-s", access_log_name, home_access_log)
    ln("-s", error_log_name, home_error_log)
    chown(user_group, access_log_name)
    chown(user_group, error_log_name)
    chown(user_group, home_access_log)
    chown(user_group, home_error_log)

    enable_domain(username, domain)
    domain_config = Config(CONFIG, username)
    domain_config.append_domain(domain)


def create_php(username, domain):
    script_name = "/etc/init.d/php-fcgi-%s" % domain
    os.system("./php_fcgi %s %s > %s" % (username, domain, script_name))
    chmod("+x", script_name)
    enable_php(username, domain)


def enable_domain(username, domain):
    config_name = "/etc/nginx/sites-enabled/%s.conf" % domain

    ln("-s", "/etc/nginx/sites-available/%s.conf" % domain,
             "/etc/nginx/sites-enabled/%s.conf" % domain)
    chown("%s:%s" % (username, username), config_name)
    ln("-s", "/etc/nginx/sites-available/%s.conf" % domain,
             "/home/%s/%s.conf" % (username, domain))


def enable_php(username, domain):
    script_name = "php-fcgi-%s" % domain
    rc_update("add", script_name)
    os.system("/etc/init.d/%s start" % script_name)


def main():
    parser = argparse.ArgumentParser(description="Add a user")

    parser.add_argument("-d", "--domain",
                        action="store",
                        dest="domain",
                        default=False,
                        help="Set a domain for the user",
                        type=str)
    parser.add_argument("username",
                        action="store",
                        default=False,
                        help="Set a username for the user",
                        type=str)
    parser.add_argument("-p", "--password",
                        action="store",
                        dest="password",
                        default=False,
                        help="Set a password for the user",
                        type=str)
    parser.add_argument("-q", "--quota",
                        action="store",
                        dest="quota",
                        default=False,
                        help="Set a limit value in KiB of space usage for the user",
                        type=int)
    parser.add_argument("-s", "--enable-php",
                        action="store",
                        dest="php",
                        default=True,
                        help="Enable php-fpm for the user",
                        type=bool)

    results = parser.parse_args()

    os.system("/etc/init.d/nginx stop")
    if results.username and (not results.password):
        results.password = getpass("Set a password: ")
    if results.username and results.password:
        create_user(results.username, results.password)
        create_database(results.username, results.password)
    if results.username and results.domain:
        create_domain(results.username, results.domain)
    if results.username and results.quota:
        create_quota(results.username, results.quota)
    if results.username and results.php:
        create_php(results.username, results.domain)
    os.system("/etc/init.d/nginx start")


main()
